package cn.blogsx.jdbc;

import java.sql.*;
import java.util.Scanner;

/**
 * 通过键盘录入用户名和密码，判断用户密码是否正确，提示是否登陆成功
 */
public class Demo3LoginExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String username = sc.nextLine();
        System.out.println("请输入密码：");
        String password = sc.nextLine();
        if(login2(username,password)){
            System.out.println("登陆成功！");
        }else {
            System.out.println("用户名或密码错误！");
        }
    }
    public static boolean login(String userName,String password) {
        if(userName ==null || password==null){
            return false;
        }
        Connection connection=null;
        Statement stmt=null;
        ResultSet resultSet=null;
        try {
            connection = JDBCUtils.getConnection();
            String sql = "select * from user where username = '" + userName + "' and password = '" +password+"' ";
            System.out.println(sql);
            stmt = connection.createStatement();
            resultSet = stmt.executeQuery(sql);
            return resultSet.next();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(resultSet,stmt,connection);
        }
        return false;
    }
    //使用PreparenStatement 实现,可以避免sql注入问题
    public static boolean login2(String userName,String password) {
        if(userName ==null || password==null){
            return false;
        }
        Connection connection=null;
        PreparedStatement pstmt=null;
        ResultSet resultSet=null;
        try {
            connection = JDBCUtils.getConnection();
            String sql = "select * from user where username = ? and password = ? ";
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1,userName);
            pstmt.setString(2,password);

            resultSet = pstmt.executeQuery();
            return resultSet.next();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(resultSet,pstmt,connection);
        }
        return false;
    }
}
